<template>
  <div class="container">
    <el-divider content-position="left">宽度设置</el-divider>
    <el-radio-group v-model="styleObj.flex" class="ml-4">
      <el-radio-button label="1">自适应</el-radio-button>
      <el-radio-button label="0">百分比</el-radio-button>
      <el-radio-button label="2">具体值</el-radio-button>
    </el-radio-group>
    <template v-if="styleObj.flex !== '1'">
      <el-divider content-position="left">具体宽度({{ styleObj.flex === '0' ? "%" : "px" }})</el-divider>
      <el-slider v-model="styleObj.width" show-input :min="10" :max="styleObj.flex === '0' ? 100 : 1000" />
    </template>

    <template v-if="isShowPosition">
      <el-divider content-position="left">布局方向</el-divider>
      <el-radio-group v-model="styleObj.justifyContent" size="small">
        <el-radio-button label="flex-start">左对齐</el-radio-button>
        <el-radio-button label="flex-end">右对齐</el-radio-button>
        <el-radio-button label="center">居中</el-radio-button>
        <el-radio-button label="space-between">两端均分</el-radio-button>
      </el-radio-group>
    </template>
  </div>
</template>
<script setup>
import { onBeforeMount } from 'vue'
defineOptions({
  name: 'TextCompontent',
  inheritAttrs: false
})

const props = defineProps({
  data: {
    type: Object
  },
  isShowPosition: {
    type: Boolean,
    default: false
  }
})

onBeforeMount(() => {
  const { style } = data.value
  if (Object.keys(data.value.style).length !== 0) {
    if (style?.flex !== '1') {
      styleObj.flex = style.flex.includes('%') ? '0' : '2'
      styleObj.width = Number(style.width.replace(/(%)|(px)/g, ''))
    } else {
      styleObj.flex = '1'
    }
    styleObj.justifyContent = style?.justifyContent ? style.justifyContent : 'flex-start'
  }

  watch(() => styleObj, (value) => {
    if (value) {
      data.value.style = {
        justifyContent: value.justifyContent,
        flex: value.flex,
        width: value.width
      }
      switch (value.flex) {
        case '1':
          data.value.style.flex = '1'
          delete data.value.style.width
          break
        case '0':
          data.value.style.flex = 'none'
          data.value.style.width = value.width + '%'
          break
        case '2':
          data.value.style.flex = 'none'
          data.value.style.width = value.width + 'px'
          break
      }
    }
  }, { deep: true })
})

const styleObj = reactive({
  flex: '1',
  textAlign: 'left',
  justifyContent: 'flex-start',
  width: 50
})

const { data } = toRefs(props)

</script>
<style lang="scss" scoped>
</style>
